﻿using System.Windows.Forms;
using Microsoft.Xna.Framework.Graphics;
using Rectangle = Microsoft.Xna.Framework.Rectangle;

namespace Deferred.Editor.Gui
{
    public class GraphicsDeviceControl : Control
    {
        private IGraphicsDeviceService deviceService;

        public GraphicsDevice GraphicsDevice { get { return deviceService.GraphicsDevice; } }

        public GraphicsDeviceControl()
            : base()
        {
        }

        public GraphicsDeviceControl(IGraphicsDeviceService deviceService)
            : base()
        {
            this.deviceService = deviceService;
        }

        protected override void OnCreateControl()
        {
            if (!DesignMode)
            {
                Initialize();
            }

            base.OnCreateControl();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            BeginDraw();
            Draw();
            EndDraw();
        }

        void BeginDraw()
        {
            Viewport viewport = new Viewport();

            viewport.X = 0;
            viewport.Y = 0;

            viewport.Width = ClientSize.Width;
            viewport.Height = ClientSize.Height;

            viewport.MinDepth = 0;
            viewport.MaxDepth = 1;

            GraphicsDevice.Viewport = viewport;
        }

        void EndDraw()
        {
            try
            {
                Rectangle sourceRectangle = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height);

                GraphicsDevice.Present(sourceRectangle, null, this.Handle);
            }
            catch
            {
                // Present might throw if the device became lost while we were
                // drawing. The lost device will be handled by the next BeginDraw,
                // so we just swallow the exception.
            }
        }

        protected override void OnPaintBackground(PaintEventArgs pevent) { }

        protected virtual void Initialize() { }
        protected virtual void Draw() { }
    }
}
